<template>
<!-- 管理员 -->
  <div id="Administration">
    <div id="management">
      <!--搜索框 -->
      <div id="manage-top">
        <el-input placeholder="请输入内容" v-model="value"></el-input>
        <button type="button" class="el-button el-button--primary" @click="management()">
          <i class="el-icon-search"></i>
          <span>查找</span>
        </button>
        <button type="button" class="el-button el-button--primary" @click="additions()" v-Promise="'admin:admin:create'">
          <div>
            <i class="el-icon-edit"></i>
            <span>添加</span>
          </div>
        </button>
      </div>
      <!-- 数据操作 -->
      <div id="manage-bottom">
        <el-table
          border
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          :key="id"
          v-Promise="'admin:admin:list'"
        >
          <el-table-column label="管理员id" prop="id"></el-table-column>
          <el-table-column label="管理员名" prop="username"></el-table-column>
          <el-table-column label="管理员头像" prop="name"></el-table-column>
          <el-table-column label="管理员角色">
            <template slot-scope="scope">
              <span v-for="item in scope.row.roleIds" :key="item">
                <el-tag>{{itemsid.find(k=>k.id==item)?itemsid.find(k=>k.id==item).name:item}}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column align="right" label="操作" style=" width: 2010px;">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="compile(scope.$index,scope.row)"
                class="kohlrabiblue"
                v-Promise="'admin:admin:update'"
              >编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)"  v-Promise="'admin:admin:delete'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <el-pagination
          :page-sizes="[10, 20, 30, 40, 50,100]"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <div>
        <!-- 添加编辑弹框 -->
        <el-dialog :title="titleName" :visible.sync="dialogFormVisible">
          <!-- 登录 -->
          <div class="loginRight">
            <div class="login-right">
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item prop="username">
                  <div class="login-img">登录名</div>
                  <el-input v-model.number="ruleForm.username" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <div class="login-img">密码</div>
                  <!-- 密码 -->
                  <el-input
                    placeholder="请输入密码"
                    show-password
                    v-model="ruleForm.password"
                    type="password"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="phone">
                  <div class="login-img">手机号</div>
                  <!-- 手机号 -->
                  <el-input v-model.number="ruleForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <!-- 真实姓名 -->
                <el-form-item prop="realname">
                  <div class="login-img">真实姓名</div>
                  <el-input v-model.number="ruleForm.realname" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <!-- 授权角色 -->
                <el-form-item label="授权角色">
                  <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
                    <el-option
                      v-for="item in itemsid"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="affirm()">
              <div>确 定</div>
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import admin from "@/api/admin.js";
import role from "@/api/role.js";
import qs from "qs";
export default {
  data() {
    //   账号
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空！"));
      } else {
        callback();
      }
    };
    //密码
    var validatePass = (rule, value, callback) => {
      let pass = /^[0-9]{6,18}$/;
      if (!value) {
        callback(new Error("密码不能为空,请输入密码！"));
      }
      if (!pass.test(value)) {
        return callback(new Error("密码必须是数字6~18位"));
      } else {
        callback();
      }
    };
    //手机号
    var message = (rule, value, callback) => {
      let mark = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("手机号不能为空！"));
      }
      if (!mark.test(value)) {
        return callback(new Error("手机号必须是1开头的数字号码！"));
      } else {
        callback();
      }
    };
    // 真实姓名
    var varealname = (rule, value, callback) => {
      let name = /^[\u4E00-\u9FA5]{1,}$/;
      if (!value) {
        callback(new Error("真实姓名不能为空！"));
      }
      if (!name.test(value)) {
        return callback(new Error("真实姓名必须是中文！"));
      } else {
        callback();
      }
    };
    return {
      //
      id: "",
      value: "",
      search: "",
      tableData: [{}],
      tableDatas: [],
      itemsid: [{}],
      dialogTableVisible: false,
      dialogFormVisible: false, //弹窗口
      FormVisible: false, //弹窗口
      titleName: "", //是否添加还是编辑
      currentPage: 1, //当前的默认的页数
      eachpage: 10, //默认的页码
      total: 0, //初始值共数据条
      totalPageNo: 1,
      ider: 0,
      value1: [],
      form: {
        name: "",
        region: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        phone: ""
      },
      //
      roleIds: "",
      ruleForm: {
        username: "",
        password: "",
        phone: "",
        realname: "",
        roleIds: ""
      },
      rules: {
        password: [
          {
            validator: validatePass,
            trigger: "blur"
          }
        ],
        username: [
          {
            validator: checkAge,
            trigger: "blur"
          }
        ],
        phone: [
          {
            validator: message,
            trigger: "blur"
          }
        ],
        realname: [
          {
            validator: varealname,
            trigger: "blur"
          }
        ]
      },
      ischecked: false
    };
  },
  methods: {
    // 页码条
    handleSizeChange(val) {
      this.eachpage = val;
      this.management();
    },
    // 页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.management();
    },
    //编辑
    compile(index, row) {
      console.log(row);
      this.dialogFormVisible = true;
      this.titleName = "编辑";
      this.modalType = "update";
      this.ider = index;
      this.form.name = row.name;
      this.ruleForm={...row}
      this.form.desc = row.desc;
    },
    //添加
    additions() {
      this.titleName = "添加";
      this.modalType = "add";
      this.dialogFormVisible = true;
      this.ruleForm={}
    },
    list() {
      let _this = this;
      role.role().then(function(res) {
        //数据
        _this.tableDatas = res.data.data.items;
      });
    },
    // 管理员数据列表
    management() {
      let _this = this;
      let data = {
        username: _this.value,
        page: _this.currentPage,
        limit: _this.eachpage
      };
      admin.admin(data).then(function(res) {
        console.log(res)
        _this.tableData = res.data.data.items;
        _this.total = res.data.data.count;
        // 分页
        _this.currentPage = res.data.data.pageNo;
        _this.eachpage = res.data.data.pageSize;
        _this.total = res.data.data.total;
        _this.totalPageNo = res.data.data.totalPageNo;
      });
    },
    // 判断是否添加还是编辑
    affirm() {
      let _this = this;
      if (
        _this.ruleForm.username == "" ||
        _this.ruleForm.password == "" ||
        _this.ruleForm.phone == "" ||
        _this.ruleForm.realname == ""
      ) {
        _this.$message.error("操作取消或失败！");
      } else {
        //添加
        if (_this.titleName === "添加") {
          admin.addition(_this.ruleForm).then(function(res) {
            if (res.data.errmsg == "成功") {
               _this.management()
               _this.$information.success("这是一条添加失败的提示消息") 
            } else {
                _this.$information.error("这是一条添加失败的提示消息") 
            }
          });
        }
        // 编辑
        if (_this.titleName === "编辑") {
          admin.compile(_this.ruleForm).then(function(res) {
            console.log(res.data)
             _this.management()
            _this.$information.success("这是一条编辑成功的提示消息")
          });
        }
      }
      _this.dialogFormVisible = false;
    },
    // // 删除
    handleDelete(index, row) {
      var _this = this;
      // 提示框
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           _this.$information.success("删除成功")
          let data = {
            id: _this.tableData[index].id
          };
          admin.handleDelete(data).then(function(res) {
            console.log(res);
            _this.tableData.splice(index, 1);
          });
        })
        .catch(() => {
           _this.$information.error("已取消删除")
        });
    }
  },
  created() {
    this.management();
    role.role().then(res => {
      this.itemsid = res.data.data.items;
    });
  },
   watch:{
    dialogFormVisible(){
      this.$nextTick(() => {
       this.$refs.ruleForm.clearValidate();
      })
    }
  }
};
</script>

<style>
#Administration {
  width: 100%;
  height: 100%;
}
#management {
  width: 80vw;
  height: 80vh;
  margin: auto;
}
/* 搜索框 */
#manage-top {
  width: 50vw;
  display: flex;
  margin-bottom: 30px;
}
#manage-top .el-input__inner {
  width: 200px;
}
.el-input {
  width: 210px;
}

/* 表格样式*/
#block {
  margin-top: 30px;
}
.kohlrabiblue {
  background: #66b1ff;
  color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
  text-align: center;
}
.el-table/deep/th.is-sortable {
  cursor: pointer;
  text-align: center;
}
.el-table td,
.el-table/deep/th.is-leaf {
  text-align: center;
}
/*  */
.loginRight {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 0px 8px 8px 0px;
}
.login-right {
  width: 80%;
  margin: auto;
}
.loginRight .login-title {
  color: #333;
  margin-bottom: 40px;
  font-weight: 500;
  font-size: 22px;
  text-align: center;
  letter-spacing: 4px;
  margin-top: 40px;
}
.el-form-item/deep/input {
  background: transparent;
  border-radius: 0;
  color: #333;
  display: inline;
}
.el-form-item {
  position: relative;
}
.el-form-item/deep/i {
  display: inline;
}
.login-img {
  position: absolute;
  top: 2px;
  left: -60px;
}

.el-checkbox {
  width: 300px;
  margin: 20px 0px 30px 0px;
}
</style>